package com.feicheng.iou.sms;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.feicheng.iou.sms.util.ConstantPropertiesUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author tianchunlei
 * @Des //短信发送
 * @Date 2021/7/23
 **/
@Component
public class SMSService {

    /**
     * @return
     * @Author tianchunlei
     * @Description //整合阿里云短信发送
     * @Date 2021/7/23 16:36
     * @Param
     */
    public boolean sendSMS(String phone, String name, String msg) {

        //设置相关参数
        DefaultProfile profile = DefaultProfile.getProfile(
                ConstantPropertiesUtils.REGION_ID,
                ConstantPropertiesUtils.ACCESS_KEY_ID,
                ConstantPropertiesUtils.SECRET
        );

        DefaultAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //手机号设置
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称
        request.putQueryParameter("SignName", ConstantPropertiesUtils.SIGN_NAME);
        //模版CODE
        request.putQueryParameter("TemplateCode", ConstantPropertiesUtils.TEMPLATE_CODE);

        //发送的内容,必须是JSON格式
        Map<String, String> params = new HashMap<>();
        params.put("name", name);
        params.put("store", msg);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(params));

        //调用方法进行短信发送
        try {

            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();

        } catch (ClientException e) {
            e.printStackTrace();
        }

        return false;
    }
}
